﻿namespace AcctrueWMS.Foundation.Render
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Text.RegularExpressions;
    using AcctrueWMS.Foundation.Web;

    public class TemplateManager : ITemplateManager
    {
        public Collection<ModelTemplate> LoadTemplates(string path)
        {
            try
            {
                Collection<ModelTemplate> coll_temp = null;
                System.IO.DirectoryInfo dictinfo = new System.IO.DirectoryInfo(path);
                FileInfo[] files = dictinfo.GetFiles("*.htm");
                if (files.Length > 0)
                {
                    coll_temp = new Collection<ModelTemplate>();
                    foreach (FileInfo item in files)
                    {
                        string fullpath = path + item.Name;
                        ModelTemplate t = LoadTemplate(fullpath);
                        t.FilePath = fullpath;
                        coll_temp.Add(t);
                    }
                }
                return coll_temp;
            }
            catch (Exception ex)
            {
                throw new Exception("AcctrueWMS.Foundation.Render.TemplateManager:\r\n" + ex.Message);
            }
        }
        /// <summary>
        /// 获取模板文件全路径
        /// </summary>
        /// <param name="templateName"></param>
        /// <returns></returns>
        public string GetTemplateFile(string templateName)
        {
            return Runtime.TemplateFilePath + "\\" + templateName.Trim() + ".htm";
        }

        public ModelTemplate LoadTemplate(string fullpath)
        {
            ModelTemplate t = new ModelTemplate();

            //加载DataModel属性
            FileStream fs = null;
            if (AcctrueWMS.Foundation.Web.Runtime.IsExistFile(fullpath))
            {
                fs = new FileStream(fullpath, FileMode.Open);
            }
            if (fs != null)
            {
                StreamReader sr = new StreamReader(fs);
                t.InnerText = sr.ReadToEnd();
                //加载片断
                t.Sections = new Dictionary<string, SectionItem>();
                t.InnerText=ProcessSection(t.InnerText, t);
                //加载元数据
                t.Meta = new Dictionary<string, string>();
                t.InnerText = ProcessMeta(t.InnerText, t);               
                
                t.FilePath = fullpath;
                sr.Close();
                fs.Close();
            }
            return t;
        }

        #region 处理Meta节
        Regex meta_reg = new Regex(@"(?!#)\[\[(?<meta>((?!\[\[).)*)\]\](?<!#)");
        /// <summary>
        /// 处理Meta节,处理完成后 抛弃Meta节
        /// </summary>
        /// <param name="html"></param>
        /// <param name="template"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public string ProcessMeta(string html, ModelTemplate template)
        {
            if (meta_reg.IsMatch(html))
            {
                foreach (Match m in meta_reg.Matches(html))
                {
                    Regex metaItem_reg = new Regex("(?<name>[\\w|\\d]+)=\"(?<value>[^\"]+)\"");
                    foreach (Match itemMatch in metaItem_reg.Matches(m.Groups["meta"].Value))
                    {
                        if (template.Meta == null)
                            template.Meta = new Dictionary<string, string>();
                        template.Meta.Add(itemMatch.Groups["name"].Value, itemMatch.Groups["value"].Value);
                    }
                }
                html = meta_reg.Replace(html, new MatchEvaluator(ReplaceBrack));
            }
            return html;
        }
        #endregion

        #region 处理Section节
        /// <summary>
        /// 处理Section节,处理完成后,抛弃Section节
        /// </summary>
        Regex section_reg = new Regex(@"\[\[section:(?<secName>[\w|\d]+)\s*{\]\](?<text>((?!\[\[).)*)\[\[}\]\]", RegexOptions.Singleline);
        public string ProcessSection(string html, ModelTemplate template)
        {
            if (section_reg.IsMatch(html))
            {
                foreach (Match m in section_reg.Matches(html))
                {
                    if (template.Sections == null)
                        template.Sections = new Dictionary<string, SectionItem>();
                    if (!template.Sections.ContainsKey(m.Groups["secName"].Value))
                        template.Sections.Add(m.Groups["secName"].Value, new SectionItem()
                        {
                            SectionName = m.Groups["secName"].Value,
                            InnerText = m.Groups["text"].Value
                        });

                }
            }
            html = section_reg.Replace(html, new MatchEvaluator(ReplaceSection));
            return html;
        }
        /// <summary>
        /// 将Section内容替换
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        string ReplaceSection(Match m)
        {
            return m.Groups["text"].Value;
        }
        #endregion

        static string ReplaceBrack(Match m)
        {
            return string.Empty;
        }
        
    }
}
